package socket

import (
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"time"
)

type WebsocketClient interface {
	Connect(url string) error
	WriteMessage(msgType int, data []byte) error
	ReadMessage() (int, []byte, error)
	Close() error
}

type GorillaWebsocketClient struct {
	conn *websocket.Conn
}

func (c *GorillaWebsocketClient) Connect(url string) error {
	dialer := websocket.Dialer{
		HandshakeTimeout: 10 * time.Second,
	}
	conn, _, err := dialer.Dial(url, nil)
	if err != nil {
		return err
	}
	c.conn = conn
	return nil
}

func (c *GorillaWebsocketClient) WriteMessage(msgType int, data []byte) error {
	err := c.conn.WriteMessage(msgType, data)
	if err != nil {
		return err
	}
	return nil
}

func (c *GorillaWebsocketClient) ReadMessage() (int, []byte, error) {
	msgType, data, err := c.conn.ReadMessage()
	if err != nil {
		return msgType, nil, err
	}
	return msgType, data, nil
}

func (c *GorillaWebsocketClient) Close() error {
	return c.conn.Close()
}

func main() {
	client := &GorillaWebsocketClient{}

	err := client.Connect("ws://echo.websocket.org/")
	if err != nil {
		log.Fatal(err)
	}

	defer client.Close()

	err = client.WriteMessage(websocket.TextMessage, []byte("hello"))
	if err != nil {
		log.Fatal(err)
	}

	_, data, err := client.ReadMessage()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Received message: %s\n", string(data))
}
